import 'package:audioplayers/audioplayers.dart';
import 'package:auto_route/annotations.dart';
import 'package:flutter/material.dart';
import 'package:lyps_music/request/api.dart';
import 'package:lyps_music/request/index.dart';
import 'package:lyps_music/store/index.dart';
import 'package:provider/provider.dart';

/// 在线音乐
@RoutePage()
class LineListPage extends StatefulWidget {
  const LineListPage({super.key});

  @override
  State<StatefulWidget> createState() => _LineListPageState();
}

class _LineListPageState extends State<LineListPage> {
  int selectIndex = 0;

  @override
  void initState() {
    super.initState();
    Api.getMusicList().then((res) {
      
      // ignore: use_build_context_synchronously
      context.read<Store>().musicList = res.data['data']['list'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Selector<Store, List<dynamic>>(
        selector: (p0, p1) => p1.musicList,
        builder: (context, mlist, child) {
          return DataTable(
            showCheckboxColumn: false,
            headingTextStyle: TextStyle(color: Colors.white, fontSize: 16),
            dataTextStyle: TextStyle(color: Colors.white, fontSize: 14),
            dividerThickness: 0,
            horizontalMargin: 0,
            border: const TableBorder(horizontalInside: BorderSide.none, verticalInside: BorderSide.none),
            columns: const [
              DataColumn(label: Text("歌名")),
              DataColumn(label: Text("")),
              DataColumn(label: Text("歌手")),
              DataColumn(label: Text("专辑")),
            ],
            rows: mlist.map((item) {
              return DataRow(
                  selected: mlist.indexOf(item) == selectIndex,
                  color: mlist.indexOf(item) == selectIndex ? WidgetStatePropertyAll(Colors.black.withOpacity(0.3)) : null,
                  onSelectChanged: (value) async {
                    if (value != null && value) {
                      setState(() {
                        selectIndex = mlist.indexOf(item);
                        context.read<Store>().currentMusic = item;
                      });
                      var player = context.read<Store>().audioplayer;
                      if (player.state == PlayerState.playing) await player.stop();
                      await player.play(UrlSource("${MyRequest.dio.options.baseUrl}${item['path']}"));
                    }
                  },
                  mouseCursor: const WidgetStatePropertyAll(SystemMouseCursors.click),
                  cells: [
                    DataCell(Text(item['name'])),
                    DataCell(Text("")),
                    DataCell(Text(item['id3'] != null ? item['id3']['ID3V1']['author'] : '未知')),
                    DataCell(Text(item['id3'] != null ? item['id3']['ID3V1']['album'] : '未知')),
                  ]);
            }).toList(),
          );
        },
      ),
    );
  }
}
